const router = require("koa-router")();
const User = require("./../models/usersSchema");
const utils = require("./../utils/utils");
const jwt = require("jsonwebtoken");

router.prefix("/user");
// 登录请求
router.post("/login", async (ctx, next) => {
  try {
    const { userName, password } = ctx.request.body;
    let res = await User.findOne({ userName, password }, "nickName");
    console.log(res);
    // 生成token
    if (res) {
      const data = res._doc;
      const token = jwt.sign({ data }, "Mumei", { expiresIn: 10 });
      data.token = token;
      ctx.body = utils.success(data);
    } else {
      ctx.body = utils.fail("密码错误", "fail", 20001);
    }
  } catch (error) {
    ctx.body = utils.fail(error);
  }
});

module.exports = router;
